package com.leaf.lowcode.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.DoorFunctionApi;
import com.leaf.lowcode.API.DoorGateApi;
import com.leaf.lowcode.entity.Dooreven;
import com.leaf.lowcode.entity.Doorlist;
import com.leaf.lowcode.entity.Doorstate;
import com.leaf.lowcode.entity.door_control.EventsRequest;
import com.leaf.lowcode.entity.door_control.GetDoorStateRequest;
import com.leaf.lowcode.mapper.DoorlistMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * 获取门禁点事件和状态
 */
@Component
public class SendDoorUp {
    @Autowired
  private  DoorlistMapper doorlistMapper;
 //@Scheduled(initialDelay = 20*100,fixedRate = 15*100)
 //@Scheduled(fixedRate = 200*1000)
    void execute()
    {

        System.out.println("获取门禁点事件和状态");
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        DoorGateApi doorGateApi = new DoorGateApi();
        GetDoorStateRequest getDoorStateRequest = null;
        DoorFunctionApi doorFunctionApi = new DoorFunctionApi();
        EventsRequest eventsRequest = null;
        List<Doorlist> doorlists = doorlistMapper.selectList(null);
        Iterator<Doorlist> iterator = doorlists.iterator();

        //获取门禁点列表
        while (iterator.hasNext())
        {
            Doorstate doorstate = new Doorstate();
            getDoorStateRequest = new GetDoorStateRequest();
            eventsRequest= new EventsRequest();
            ArrayList<String> doorindex=new ArrayList<String>();



            Doorlist doorlist = iterator.next();
            doorindex.add(doorlist.getDoorIndexCode());
            getDoorStateRequest.setDoorIndexCodes(doorindex);
            eventsRequest.setDoorIndexCodes(doorindex);
            eventsRequest.setPageNo(10);
            eventsRequest.setPageSize(100);
            /**
             * 查询门禁状态
             */
            String doorstates = doorGateApi.doorstates(getDoorStateRequest);
            /**
             * 查询门禁点事件
             */
            String events = doorFunctionApi.events(eventsRequest);
            System.out.println("iterator.next();"+iterator.next().getDoorIndexCode());
            System.out.println(events);
            JSONObject doorstatesjson = JSONObject.parseObject(doorstates);
            JSONArray liststate = (JSONArray) ((JSONObject) doorstatesjson.get("data")).get("authDoorList");
            for (int i = 0; i < liststate.size(); i++) {
                JSONObject json1 = (JSONObject) liststate.get(i);
                Field[] fields = doorstate.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //System.out.println(field.getName());
                    Iterator<String> iterator1= json1.keySet().iterator();
                    while (iterator1.hasNext()) {
                        String name = iterator1.next();
                        if (field.getName().equals(name)) {
                            Object o = json1.get(name);
                       //     System.out.println("O========="+o);
                            if (field.getType().toString().equals("class java.lang.String")) {
                                String o1;
                                if(o==null)
                                {
                                    o1="";

                                }else
                                {
                                    o1 = o.toString();
                                }
                                try {
                                    field.setAccessible(true);
                                    field.set(doorstate, o1);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }else if(field.getType().toString().equals("class java.lang.Integer"))
                            {
                                Integer o1=null;
                                o1=Integer.valueOf(o.toString());
                                try {
                                    field.setAccessible(true);
                                    field.set(doorstate, o1);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                            else {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                                Date ts = null;
                                try {
                                    ts = sdf.parse((String) o);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                try {
                                    field.setAccessible(true);
                                    field.set(doorstate, ts);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                //状态和事件分开查询，然后统一上传，两者是不一样的路径
             //   System.out.println("doorStatus"+doorstate.getDoorState());
            }


            JSONObject evenjson = JSONObject.parseObject(events);
            JSONArray listeven = (JSONArray) ((JSONObject) evenjson.get("data")).get("list");
            List<Dooreven> arrylistenve=new  ArrayList<Dooreven>();
            for (int i = 0; i < listeven.size(); i++) {
                Dooreven dooreven = new Dooreven();
                JSONObject json1 = (JSONObject) listeven.get(i);
                Field[] fields = dooreven.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //System.out.println(field.getName());
                    Iterator<String> iterator1= json1.keySet().iterator();
                    while (iterator1.hasNext()) {
                        String name = iterator1.next();
                        if (field.getName().equals(name)) {
                            Object o = json1.get(name);
                            if (field.getType().toString().equals("class java.lang.String")) {
                                String o1;
                                if(o==null)
                                {
                                    o1="";

                                }else
                                {
                                    o1 = o.toString();
                                }
                                try {
                                    field.setAccessible(true);
                                    field.set(dooreven, o1);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }else if(field.getType().toString().equals("class java.lang.Integer"))
                            {
                                Integer o1=null;
                                o1=Integer.valueOf(o.toString());
                                try {
                                    field.setAccessible(true);
                                    field.set(dooreven, o1);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                            else {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                                Date ts = null;
                                try {
                                    ts = sdf.parse((String) o);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                try {
                                    field.setAccessible(true);
                                    field.set(dooreven, ts);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                //状态和事件分开查询，然后统一上传，两者是不一样的路径
              //  System.out.println("doorStatus"+dooreven.getDevName());
                arrylistenve.add(dooreven);
            }

            if(subDeviceDTOList!=null) {
                for (SubDeviceDTO dto : subDeviceDTOList) {
                    String pid = dto.getPid();
                    String sn = dto.getSn();
                    String din = dto.getDin();
                if(doorlist.getDoorIndexCode().equals(sn))
                {
                    for(int i=0;i<arrylistenve.size();i++) {
                        Dooreven dooreven = arrylistenve.get(i);
                   //     System.out.println("sn=====" + doorlist.getDoorIndexCode());
                        JSONObject standardData = new JSONObject();
                        standardData.put("reportTs", System.currentTimeMillis());
                        JSONObject profile = new JSONObject();
                        profile.put("modelID", "200418");
                        profile.put("poiCode", "w0703000");
                        standardData.put("profile", profile);
                        WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                        JSONObject properties = new JSONObject();
                        JSONObject propertie = new JSONObject();
                        JSONObject even = new JSONObject();
                        JSONObject evens = new JSONObject();
                        propertie.put("DoorIndexCode", doorstate.getDoorIndexCode());
                        propertie.put("doorstate", doorstate.getDoorState());
                        propertie.put("DoorName", dooreven.getDoorName());
                        properties.put("DoorInfo", propertie);
                        standardData.put("properties", properties);
                        even.put("evenName",dooreven.getEventName());
                        even.put("eventTime",dooreven.getEventTime());
                        even.put("receiveTime",dooreven.getReceiveTime());
                        even.put("readerDevName",dooreven.getReaderDevName());
                        even.put("personName",dooreven.getPersonName());
                        even.put("orgName",dooreven.getOrgName());
                        even.put("certNo",dooreven.getCertNo());
                        evens.put("Dooreven",even);

                        if(doorstate.getDoorIndexCode().equals("612ecaab219e47d78285d811003f60ea"))
                            System.out.println(even);

                        standardData.put("evens", evens);
                        try {

                            System.out.println("上传数据");
                            String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                           System.out.println("发送设备运行时事件数据==" + devRunEvent);
                           System.out.println("--------------------------------开始传输设备运行时事件数据");
                            wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                        } catch (Exception e) {
                            System.out.println("设备运行时事件数据传输出现异常");
                        }

                    }

                }

                }
            }

        }
    }
}
